package com.locationbasedagent.server;

import com.google.android.c2dm.server.PMF;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.web.bindery.requestfactory.server.RequestFactoryServlet;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.jdo.Query;
import javax.servlet.ServletContext;

public class DataStore {

	//populate the DataStore
	public void populateTheDataStore() {
		this.addHouseListing("2 Bed 1 Bath", "101 E San Fernando Street", "San Jose", "95122", "lbidrawn@gmail.com", "5554", "37.335341", "-121.887066", "$450,000",
				"http://i1191.photobucket.com/albums/z472/elydelan/Mom%20House/Housefront3.jpg",
				"http://i1191.photobucket.com/albums/z472/elydelan/Mom%20House/Fronthouse.jpg", 
				"http://i1191.photobucket.com/albums/z472/elydelan/Mom%20House/Housefront2.jpg",
				"http://i1191.photobucket.com/albums/z472/elydelan/Mom%20House/Backofhouse1.jpg", 
				"http://i1191.photobucket.com/albums/z472/elydelan/Mom%20House/Backofhouse2.jpg",
				"http://www.marmondesign.com/cmpe235/home1.3gp");
		this.addHouseListing("3 Bed 2 Bath", "42 S 8th Street #2", "San Jose", "95122", "lbidrawn@gmail.com", "5554", "37.339042", "-121.882215", "$700,000", 
				"http://i2.photobucket.com/albums/y10/digihore/Houses/Perfect%20House/front.jpg", 
				"http://i2.photobucket.com/albums/y10/digihore/Houses/Perfect%20House/yardpatiowall.jpg", 
				"http://i1140.photobucket.com/albums/n579/stevenshomeforsale/House043.jpg", 
				"http://i1140.photobucket.com/albums/n579/stevenshomeforsale/House046.jpg", 
				"http://i1140.photobucket.com/albums/n579/stevenshomeforsale/House050.jpg", 
				"http://www.marmondesign.com/cmpe235/home1.3gp");
		this.addHouseListing("4 Bed 1 Bath", "1300 The Alameda", "San Jose", "95126", "ruchitabora@gmail.com", "5558", 
				"37.332201", "-121.912650", "$670,000", 
				"http://i1140.photobucket.com/albums/n579/stevenshomeforsale/DSCN9583.jpg", 
				"http://i1140.photobucket.com/albums/n579/stevenshomeforsale/House038.jpg", 
				"http://i1140.photobucket.com/albums/n579/stevenshomeforsale/House043.jpg", 
				"http://i1140.photobucket.com/albums/n579/stevenshomeforsale/House046.jpg", 
				"http://i1140.photobucket.com/albums/n579/stevenshomeforsale/House047.jpg", 
				"http://www.marmondesign.com/cmpe235/home2.3gp");
		this.addHouseListing("1 Bed 1 Bath Townhouse", "1050 Benton Street", "Santa Clara", "95050", "ruchitabora@gmail.com", "5558", 
				"37.350100", "-121.946225", "$340,00", 
				"http://i1238.photobucket.com/albums/ff483/KandG2/3.jpg", 
				"http://i1238.photobucket.com/albums/ff483/KandG2/2.jpg", 
				"http://i1238.photobucket.com/albums/ff483/KandG2/1.jpg", 
				"http://i1238.photobucket.com/albums/ff483/KandG2/13.jpg", 
				"http://i1238.photobucket.com/albums/ff483/KandG2/7.jpg", 
				"http://www.marmondesign.com/cmpe235/home2.3gp");
		this.addHouseListing("2 Bed 2 Bath", "19920 Olivewood Street", "Cupertino", "95014", "ruchitabora@gmail.com", "5558", "37.332952", "-122.021932", "$450,000", 
				"http://i1143.photobucket.com/albums/n633/KenaiDelacroix/PERRYHOMES.jpg", 
				"http://i1136.photobucket.com/albums/n485/vetport189/P1000244.jpg", 
				"http://i1136.photobucket.com/albums/n485/vetport189/P1000245.jpg", 
				"http://i979.photobucket.com/albums/ae279/U_ra/HarborLofts118.jpg", 
				"http://i1142.photobucket.com/albums/n610/localseoclient57/Guest-House.jpg", 
				"http://www.marmondesign.com/cmpe235/home3.3gp");
		this.addHouseListing("2 Bed 2 Bath Townhouse", "2510 W Middlefield Road", "Mountain View", "94043", "lbidrawn@gmail.com", "5554","37.414565", "-122.100694", "$450,000", 
				"http://i1140.photobucket.com/albums/n579/stevenshomeforsale/House040-1.jpg", 
				"http://i1140.photobucket.com/albums/n579/stevenshomeforsale/House042-1.jpg", 
				"http://i1140.photobucket.com/albums/n579/stevenshomeforsale/House056.jpg", 
				"http://i1140.photobucket.com/albums/n579/stevenshomeforsale/House036.jpg", 
				"http://i1142.photobucket.com/albums/n610/localseoclient57/Guest-House.jpg", 
				"http://www.marmondesign.com/cmpe235/home4.3gp");
		
	}

  /**
   * Remove this object from the data store.
   */
  public void deleteHouseListing(Long id) {
    PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
      HouseListing item = pm.getObjectById(HouseListing.class, id);
      pm.deletePersistent(item);
    } finally {
      pm.close();
    }
  }
  
  /**
   * Add this object from the data store.
   */
  public HouseListing addHouseListing(String name, String address, String city, String zip, 
		  String agentID, String agentNumber, String latitude, String longitude, String price, String photo1, String photo2, 
		  String photo3, String photo4, String photo5, String video) {
	  
	  String userID = (agentID.length() > 0) ? agentID : this.getUserEmail();
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
      tx.begin();
      HouseListing listing = new HouseListing(name, address, city, zip, userID, agentNumber, latitude, longitude, price, 
    		  photo1, photo2, photo3, photo4, photo5, video);
      pm.makePersistent(listing);
      tx.commit();
      return listing;
    } finally {
    	if (tx.isActive())
    	{
    		tx.rollback();
    	}
      pm.close();
    }
  }
  
  public LocationBasedAgentUser addUser(String userID, String firstname, String lastname, String phonenumber, 
		  boolean isAgent, String hometown) {
	  PersistenceManager pm = PMF.get().getPersistenceManager();
	  Transaction tx = pm.currentTransaction();
	  try {
		  tx.begin();
		  LocationBasedAgentUser user = new LocationBasedAgentUser(userID, firstname, lastname, phonenumber, isAgent, hometown);
		  pm.makePersistent(user);
		  tx.commit();
		  return user;
	  } finally {
		  if (tx.isActive())
		  {
			  tx.rollback();
		  }
		  pm.close();
	  }
  }
  
  public List<LocationBasedAgentUser> findUserByID(String userID) {
	  PersistenceManager pm = PMF.get().getPersistenceManager();
	  try {
		  String queryString = "select from " + LocationBasedAgentUser.class.getName() +
		  	" where userID == '" + userID + "'";
		  Query query = pm.newQuery(queryString);
	        List<LocationBasedAgentUser> list = (List<LocationBasedAgentUser>) query.execute();
	        if (list.size() == 0)
	        {
	        	list.size();
	        }
	        return list;
	      } catch (RuntimeException e) {
	        System.out.println(e);
	        throw e;
	      } finally {
	        pm.close();
	  }
  }
  
  public List<LocationBasedAgentUser> findUsers() {
	  PersistenceManager pm = PMF.get().getPersistenceManager();
	  try {
		  String queryString = "select from " + LocationBasedAgentUser.class.getName();
		  Query query = pm.newQuery(queryString);
	        List<LocationBasedAgentUser> list = (List<LocationBasedAgentUser>) query.execute();
	        if (list.size() == 0)
	        {
	        	list.size();
	        }
	        return list;
	      } catch (RuntimeException e) {
	        System.out.println(e);
	        throw e;
	      } finally {
	        pm.close();
	  }
  }
		  
//TODO: Implement radius feature
    @SuppressWarnings("unchecked")
    public List<HouseListing> findAllWhere(String address, String city, String zip, String sellingID) {
//      if (id == null) {
//        return null;
//      }
  
      PersistenceManager pm = PMF.get().getPersistenceManager();
      try {
    	  //Construct the query string provided with the various parameters passed in
    	  //for each parameter, use a different where clause to the SQL query
    	  String queryString = "select from " + HouseListing.class.getName();
    	  boolean whereUsed = false;
    	  if (address != null && address.length() > 0)
    	  {
    		  queryString += (whereUsed) ? ", listingAddress == '" + address + "'" 
    				  : " where listingAddress == '" + address + "'";
    		  whereUsed = true;
    	  }
    	  if (city != null && city.length() > 0)
    	  {
    		  queryString += (whereUsed) ? ", listingCity == '" + city + "'" 
    				  : " where listingCity == '" + city + "'";
    		  whereUsed = true;
    	  }
    	  if (zip != null && zip.length() > 0)
    	  {
    		  queryString += (whereUsed) ? ", listingZip == '" + zip + "'" 
    				  : " where listingZip == '" + zip + "'";
    		  whereUsed = true;
    	  }
    	  if (sellingID != null && sellingID.length() > 0)
    	  {
    		  queryString += (whereUsed) ? ", sellingAgentID == '" + getUserEmail() + "'" 
    				  : " where sellingAgentID == '" + getUserEmail() + "'";
    		  whereUsed = true;
    	  }
        Query query = pm.newQuery(queryString);
        List<HouseListing> list = (List<HouseListing>) query.execute();
        if (list.size() == 0)
        {
        	list.size();
        }
        return list;
      } catch (RuntimeException e) {
        System.out.println(e);
        throw e;
      } finally {
        pm.close();
      }
    }

@SuppressWarnings("unchecked")
public List<HouseListing> findHouseByID(String id) {
  PersistenceManager pm = PMF.get().getPersistenceManager();
  try {
      Query query = pm.newQuery("select from " + HouseListing.class.getName() + " where id == " + id);
      List<HouseListing> list = (List<HouseListing>) query.execute();
      if (list.size() == 0) {
           //Workaround for this issue:
           //http://code.google.com/p/datanucleus-appengine/issues/detail?id=24
          list.size();
        }

    return list;
  } catch (RuntimeException e) {
    System.out.println(e);
    throw e;
  } finally {
    pm.close();
  }
}

  /**
   * Persist this object in the datastore.
   */
  public HouseListing updateHouseListing(HouseListing item, String name, String address, String city, String zip,
			String agentID, String agentNumber, String latitude, String longitude, String price, String photo1, String photo2, 
			String photo3, String photo4, String photo5, String video) {
	  if (name.length() > 0)
	  {
		  item.setListingName(name);
	  }
	  if (address.length() > 0)
	  {
		  item.setListingAddress(address);
	  }
	  if (city.length() > 0)
	  {
		  item.setListingCity(city);
	  }
	  if (zip.length() > 0)
	  {
		  item.setListingZip(zip);
	  }
	  if (agentID.length() > 0)
	  {
		  item.setSellingAgentID(agentID);
	  }
	  if (agentNumber.length() > 0)
	  {
		  item.setSellingAgentPhoneNumber(agentNumber);
	  }
	  if (latitude.length() > 0)
	  {
		  item.setLatitude(latitude);
	  }
	  if (longitude.length() > 0)
	  {
		  item.setLongitude(longitude);
	  }
	  if (price.length() > 0)
	  {
		  item.setListingPrice(price);
	  }
	  if (photo1.length() > 0)
	  {
		  item.setPhotoURL1(photo1);
	  }
	  if (photo2.length() > 0)
	  {
		  item.setPhotoURL2(photo2);
	  }
	  if (photo3.length() > 0)
	  {
		  item.setPhotoURL3(photo3);
	  }
	  if (photo4.length() > 0)
	  {
		  item.setPhotoURL4(photo4);
	  }
	  if (photo5.length() > 0)
	  {
		  item.setPhotoURL5(photo5);
	  }
	  if (video.length() > 0)
	  {
		  item.setVideoURL(video);
	  }
    PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
      pm.makePersistent(item);
      return item;
    } finally {
      pm.close();
    }
  }
  
  public LocationBasedAgentUser updateUserInfo(LocationBasedAgentUser item) {
	    PersistenceManager pm = PMF.get().getPersistenceManager();
	    try {
	      pm.makePersistent(item);
	      return item;
	    } finally {
	      pm.close();
	    }
  }

  public static String getUserId() {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    return user.getUserId();
  }
  
  public static String getUserEmail() {
	    UserService userService = UserServiceFactory.getUserService();
	    User user = userService.getCurrentUser();
	    return user.getEmail();
	  }
	  
  
	
  public static void sendC2DMUpdate(String message, List<LocationBasedAgentUser> users) {
//	    UserService userService = UserServiceFactory.getUserService();
//	    User user = userService.getCurrentUser();
		ServletContext context = RequestFactoryServlet.getThreadLocalRequest().getSession().getServletContext();
		for (LocationBasedAgentUser lbauser : users)
		{
			SendMessage.sendMessage(context, lbauser.getUserID(), message);
		}
		
}




}
